import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Popconfirm, Tree, Card } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { settingsApi } from '../../services/api';

interface CaseCategory {
  id: string;
  name: string;
  level: number;
  parentId: string | null;
  children?: CaseCategory[];
}

const CaseCategoryManagement: React.FC = () => {
  const [categories, setCategories] = useState<CaseCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [editingCategory, setEditingCategory] = useState<CaseCategory | null>(null);
  const [form] = Form.useForm();

  // 获取案例分类数据
  const fetchCategories = async () => {
    try {
      setLoading(true);
      const data = await settingsApi.getCaseCategories();
      // 将string[]转换为CaseCategory[]
      const categoryObjects: CaseCategory[] = data.map((name, index) => ({
        id: `category-${index}`,
        name,
        level: 1,
        parentId: null
      }));
      setCategories(categoryObjects);
    } catch (error) {
      console.error('获取案例分类失败:', error);
      message.error('获取案例分类失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  // 添加分类
  const handleAdd = () => {
    setEditingCategory(null);
    form.resetFields();
    setModalOpen(true);
  };

  // 编辑分类
  const handleEdit = (category: CaseCategory) => {
    setEditingCategory(category);
    form.setFieldsValue(category);
    setModalOpen(true);
  };

  // 保存分类
  const handleSave = async (values: any) => {
    try {
      if (editingCategory) {
        // 编辑逻辑
        await settingsApi.updateCaseCategory(editingCategory.id, values);
        message.success('分类更新成功');
      } else {
        // 添加逻辑
        await settingsApi.createCaseCategory(values);
        message.success('分类添加成功');
      }
      setModalOpen(false);
      fetchCategories();
    } catch (error) {
      console.error('保存分类失败:', error);
      message.error('保存分类失败');
    }
  };

  // 删除分类
  const handleDelete = async (id: string) => {
    try {
      await settingsApi.deleteCaseCategory(id);
      message.success('分类删除成功');
      fetchCategories();
    } catch (error) {
      console.error('删除分类失败:', error);
      message.error('删除分类失败');
    }
  };

  // 构建树形数据
  const buildTreeData = (categories: CaseCategory[]): any[] => {
    const map = new Map();
    const roots: any[] = [];

    // 创建节点映射
    categories.forEach(cat => {
      map.set(cat.id, {
        key: cat.id,
        title: (
          <div className="flex justify-between items-center">
            <span>{cat.name}</span>
            <div className="space-x-2">
              <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(cat)} />
              <Popconfirm
                title="确定删除这个分类吗？"
                onConfirm={() => handleDelete(cat.id)}
              >
                <Button size="small" danger icon={<DeleteOutlined />} />
              </Popconfirm>
            </div>
          </div>
        ),
        children: []
      });
    });

    // 构建树形结构
    categories.forEach(cat => {
      const node = map.get(cat.id);
      if (cat.parentId && map.has(cat.parentId)) {
        map.get(cat.parentId).children.push(node);
      } else {
        roots.push(node);
      }
    });

    return roots;
  };

  const treeData = buildTreeData(categories);

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <h3 className="text-lg font-semibold">案例分类管理</h3>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          添加分类
        </Button>
      </div>

      <Card>
        {loading ? (
          <div className="text-center py-8">
            <div className="text-gray-500">加载中...</div>
          </div>
        ) : treeData.length > 0 ? (
          <Tree
            treeData={treeData}
            defaultExpandAll
            showLine
            blockNode
          />
        ) : (
          <div className="text-center py-12">
            <div className="text-gray-400 text-lg mb-2">📂</div>
            <div className="text-gray-500 mb-2">暂无案例分类数据</div>
            <div className="text-gray-400 text-sm">点击上方"添加分类"按钮创建第一个分类</div>
          </div>
        )}
      </Card>

      <Modal
        title={editingCategory ? '编辑案例分类' : '添加案例分类'}
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        footer={null}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Form.Item
            label="分类名称"
            name="name"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>
          
          <Form.Item
            label="分类级别"
            name="level"
            rules={[{ required: true, message: '请选择分类级别' }]}
          >
            <Input type="number" min={1} max={3} placeholder="1-一级分类，2-二级分类，3-三级分类" />
          </Form.Item>
          
          <Form.Item
            label="父级分类ID"
            name="parentId"
          >
            <Input placeholder="留空表示一级分类" />
          </Form.Item>
          
          <div className="flex justify-end space-x-2">
            <Button onClick={() => setModalOpen(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default CaseCategoryManagement;